package org.jamin.lending.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.jamin.lending.domain.entity.Auser;
import org.jamin.lending.domain.form.LoginForm;
import org.jamin.lending.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

@Controller
public class MemberController {
	
	@Autowired
	private ManagerService managerService; 
	
	@RequestMapping(value = "admin/login",method = RequestMethod.GET)
	public String toAdminLogin(ModelMap modelMap){
		modelMap.addAttribute(new LoginForm());
		return "manager/login";
	}
	
	@RequestMapping(value = "admin/login",method = RequestMethod.POST)
	public String doAdminLogin(@Valid LoginForm loginForm,BindingResult bindingResult,HttpServletRequest request){
		Auser auser = this.managerService.adminLogin(loginForm);
		if(bindingResult.hasErrors()){
			return "manager/login";
		}
		if(auser == null){
			FieldError error = new FieldError("username", "username", "账号或密码错误");
			bindingResult.addError(error);
			return "manager/login";
		}
		WebUtils.setSessionAttribute(request, "auser", auser);
		return "redirect:/admin/index";
	}
	
	@RequestMapping(value = "admin/logout")
	public String doAdminLogout(HttpServletRequest request){
		WebUtils.setSessionAttribute(request, "auser", null);
		return "redirect:/admin/login";
	}

}
